<?php
/**
 * 央服礼包卡号管理
 */

require '../inc/init.php';
chkpurview('activity_code_manage');

$act = isset($_GET['action']) ? $_GET['action'] : 'list';
$export=isset($_GET['export']) ? $_GET['export'] : NULL;

if($export =='true')	//导出excel
{
	$sql = "SELECT c.id,t.act_type,`code` ,server_id,c.created_date,c.last_modified_date,c.status
					FROM tb_ad_activity_code AS c
					LEFT JOIN tb_actcode_type as t ON t.id = c.code_type";
	$rs = $db->getAll($sql);
	if($rs)
	{
		require_once ROOT_PATH . '/inc/phpExcel/PHPExcel/IOFactory.php';
	
		$objPHPExcel = new PHPExcel();  
		
		$objPHPExcel->setActiveSheetIndex(0);
		$objPHPExcel->getActiveSheet()->setTitle("礼包卡号列表"); 
		$objPHPExcel->getDefaultStyle()->getFont()->setName('Arial');  
		$objPHPExcel->getDefaultStyle()->getFont()->setSize(10);  
		 
		$objPHPExcel->getActiveSheet()->setCellValue('A1', 'id');
		$objPHPExcel->getActiveSheet()->setCellValue('B1', '礼包卡号类型');
		$objPHPExcel->getActiveSheet()->setCellValue('C1', '礼包卡号');
		$objPHPExcel->getActiveSheet()->setCellValue('D1', '服务器');
		$objPHPExcel->getActiveSheet()->setCellValue('E1', '生成时间');
		$objPHPExcel->getActiveSheet()->setCellValue('F1', '发送时间');
		$objPHPExcel->getActiveSheet()->setCellValue('G1', '操作状态');
		
		$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setAutoSize(true); 
		$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setAutoSize(true);
		$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setAutoSize(true);
	    $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setAutoSize(true);
	    $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setAutoSize(true);
	    $objPHPExcel->getActiveSheet()->getColumnDimension('F')->setAutoSize(true);
	    $objPHPExcel->getActiveSheet()->getColumnDimension('G')->setAutoSize(true);
	    
		$i = 2;  
		foreach($rs as $key=>$val)
		{
			 $objPHPExcel->getActiveSheet()->setCellValue('A'.$i, $val['id']);
			 $objPHPExcel->getActiveSheet()->setCellValue('B'.$i, $val['act_type']);
			 $objPHPExcel->getActiveSheet()->getCell('B'.$i)->setDataType();  
			 $objPHPExcel->getActiveSheet()->setCellValue('C'.$i, $val['code']);
			 $objPHPExcel->getActiveSheet()->getCell('C'.$i)->setDataType();  
			 $objPHPExcel->getActiveSheet()->setCellValue('D'.$i, $val['server_id']);
			 $objPHPExcel->getActiveSheet()->setCellValue('E'.$i, $val['created_date']);
			 $objPHPExcel->getActiveSheet()->setCellValue('F'.$i, $val['last_modified_date']);
			 $objPHPExcel->getActiveSheet()->setCellValue('G'.$i, $val['status']);
			 $i++;
		}
	
            header('Content-Type: application/vnd.ms-excel;charset=UTF-8');  
            header('Content-Disposition: attachment;filename="'.date('Ymdhis').'_Excel.xls"');  
            header('Cache-Control: max-age=0');  
            $objWriter =  PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');  
            $objWriter -> save('php://output');  
            exit;
	}
}
else if($act == 'make')	//生成礼包卡号			
{
	$op = isset($_GET['op']) ? $_GET['op'] : null;
	if($op == 'generate')			//生成礼品卡号
	{
		$num = isset($_POST['num']) ? intval($_POST['num']) : 500;
		$length = isset($_POST['length']) ? $_POST['length'] : 8;
		$code_types = isset($_POST['code_types']) ? $_POST['code_types'] : 0;
		while($num)
		{
			$actCode = generatePassword($length);
			$sql = "insert into tb_ad_activity_code (code,code_type,status,created_date,last_modified_date) values ('$actCode',$code_types,1,NOW(),NOW())";
			$flag = $db->query($sql);
			if(!$flag)
			{
				exit('0');
			}
			$num--;
		}
		gourl('generate success!', 'active_code.php?action=make');
	}
	
	$sql = "SELECT id,act_type FROM tb_actcode_type";
	$code_types = $db->getAll($sql);

	$code_type = isset($_GET['code_type']) ? $_GET['code_type'] : NULL;
	$T->assign('act',$act);
	$T->assign('code_type',$code_type);
	$T->assign('code_types',$code_types);
	$T->display('active_code.html');
	exit;
}
elseif($act == 'type') 			//礼包卡类型
{
	$op = isset($_GET['op']) ? $_GET['op'] : null;
	if($op == 'add')					//添加新的礼品卡类型
	{
		$code_type_name = isset($_POST['code_type_name']) ? trim(strip_tags($_POST['code_type_name']) ): NULL;

		if(empty($code_type_name))
		{
			gourl('field_empty', 'active_code.php');
		}
		
		if(strlen($code_type_name)>30)
		{
			gourl('font_toomany', 'active_code.php');
		}
		
		$sql = "INSERT INTO tb_actcode_type SET act_type = '$code_type_name'";
		$isAdded = $db->query($sql);
	}
	elseif($op== 'delete')				//删除礼品卡类型
	{
		$type_id = isset($_GET['typeId']) ?$_GET['typeId'] : null;
		
		$sql = "SELECT * FROM tb_ad_activity_code WHERE code_type = $type_id";
		$flag = $db->getOne($sql);
		if($flag)
		{
			gourl('Please delete codes of selected code_type first!', 'active_code.php');
		}
		
		$sql = "DELETE FROM tb_actcode_type WHERE id = $type_id";
		$isDeleted = $db->query($sql);
	}
	
	$sql = "SELECT id,act_type FROM tb_actcode_type WHERE id>1000";			//普通礼品卡号大于1000，防止和三种已有类型混淆
	$actTypes = $db->getAll($sql);
	
	$T->assign('act',$act);
	$T->assign('actTypes',$actTypes);
	$T->display('active_code.html');
	exit;
}
elseif($act == 'list')				//激活码列表
{
	$op = isset($_GET['op']) ? $_GET['op'] : null;
	$where = '';
	$url = '?';
	
	if($op == 'filter' )			//过滤
	{
		$url .= 'op=filter&';
		//礼包卡号过滤
		$act_code = isset($_REQUEST['act_code']) ? $_REQUEST['act_code'] : NULL;
		if(!empty($act_code))
		{
			$where .= " and c.code = '$act_code'";
			$url .= "act_code=$act_code&";
		}
		$T->assign('act_code',$act_code);
		
		//生成时间过滤
		$generate_time = isset($_REQUEST['generate_time']) ? $_REQUEST['generate_time'] : NULL;
		if(!empty($generate_time))
		{
			$where .= " and c.created_date = '$generate_time'";
			$url .= "generate_time=$generate_time&";
		}
		$T->assign('generate_time',$generate_time);
		
		//发送时间过滤
		$send_time = isset($_REQUEST['send_time']) ? $_REQUEST['send_time'] : NULL;
		if(!empty($send_time))
		{
			$where .= " and c.last_modified_date = '$send_time'";
			$url .= "send_time=$send_time&";
		}
		$T->assign('send_time',$send_time);
		
		//礼包卡类型过滤
		$codeType = isset($_REQUEST['codeTypes']) ? $_REQUEST['codeTypes'] : 0;
		if(!empty($codeType))
		{
			$where .= " and c.code_type = $codeType";
			$url .= "codeTypes=$codeType&";
		}
		$T->assign('codeType',$codeType);
		
		//是否使用过滤
		$is_used = isset($_REQUEST['is_used']) ? $_REQUEST['is_used'] : 0;
		if(!empty($is_used))
		{
			$where .= " and c.status = $is_used"; 
			$url .= "is_used=$is_used&";
		}
		$T->assign('is_used',$is_used);

		//目标服务器过滤
		$server = isset($_REQUEST['server']) && !empty($_REQUEST['server']) ? $_REQUEST['server'] : 0;			//0:全部；1:未使用；2：已使用
		if(!empty($server))
		{
			$where .= " and c.server_id  REGEXP $server";
			$url .= "server=$server&";
		}
		$T->assign('server',$server);
		
	}
	
	$sql = "SELECT id,code,status FROM tb_ad_activity_code as c WHERE 1 ".$where;
	$codes = $db->getAll($sql);
	$sql = "SELECT code  FROM tb_ad_activity_code as c WHERE 1 ".$where;
	$codeArray = $db->getTotal($sql);
	//将过滤后的卡号发送至指定单服	
	if(($op == 'filter' && isset($_POST['send'])) || ($op == 'filter' && isset($_POST['remote_delete'])))
	{
		$platforms = isset($_POST['platform_id']) ?$_POST['platform_id']:0;
		$servers = isset($_POST['server_id'])? $_POST['server_id']:0;
		
		//没有指定目标服务器
		if(empty($servers))
		{
			gourl('please input servers!', 'active_code.php?action=list');
		}
		
		//没有指定礼品卡类型
		if(empty($codeType))
		{
			gourl('please input codetype!', 'active_code.php?action=list');
		}
		
		//检测选定的礼品卡是否都已经发送
		if(isset($_POST['remote_delete']))
		{
			$codes = check_is_send($codes,0);		//都已发送的才删除
		}
		else 
		{
			$codes = check_is_send($codes,1);		//都未发送的才发送
		}
		
		//礼品卡号都已使用，已发送
		if(empty($codes))
		{
			gourl('The codes have been send!', 'active_code.php?action=list');
		}
		
		$action = isset($_POST['remote_delete']) ? 2 : 1;		//1:默认add  2:删除
		
		//循环发送
		$msg = '';
		foreach($servers as $k=>$v)
		{
			$params['act'] = 'activityPackageOpt';
			$params['action'] = $action;
			$params['codeType'] = $codeType;
			$params['codeArray'] = json_encode($codeArray);
			$send_url = 'https://' . getServerById($v) . '/task/activity_api.php';
			$retcode = makeRequest($send_url, $params);
			if($retcode == 0)
			{
				$msg .= getServerNameById($v).'发送失败!\n';
			}
			else 
			{
				$msg .= getServerNameById($v).'发送成功!\n';
			}
		}
		
		//全部发送成功后，重置数据库改激活码的状态，以及发送到的目标服务器
		if($action == 1)
		{
			code_send_status('add',$codes,$servers);
		}
		else 
		{
			code_send_status('del',$codes,$servers);
		}
		
		//全部发送成功
		gourl($msg, 'active_code.php?action=list');
		
	}
	else 	if($op == 'filter' && isset($_POST['local_delete']))
	{
		if(empty($codes))
		{
			gourl('please input codes!', 'active_code.php?action=list');
		}
		
		$codes = check_is_send($codes, 1);
		if(empty($codes))
		{
			gourl('The selected codes are sended,So not allowed deleted in localServer!', 'active_code.php?action=list');
		}
		
		code_send_status('delete', $codes, $server);
		
		gourl('The selected codes are  deleted in localServer!', 'active_code.php?action=list');
		
	}
	
	$sql = "SELECT c.id,t.act_type,`code` ,server_id,c.created_date,c.last_modified_date,c.status
			FROM tb_ad_activity_code AS c
			LEFT JOIN tb_actcode_type as t ON t.id = c.code_type
			WHERE 1 ".$where;
	$codes = array();
	$page = isset($_GET['page']) && $_GET['page'] >= 1 ? $_GET['page'] : 1;
	$pagesize = 12;
	$rs = $db->getAll($sql,$page,$pagesize);
	$count = $db->getOne('select count(*)   FROM tb_ad_activity_code AS c LEFT JOIN tb_actcode_type as t ON t.id = c.code_type WHERE 1'.$where);
	foreach($rs as $k=>$v)
	{
		$codes[$k] = $v;
		$codes[$k]['server_id'] = explainServerName($v['server_id']);
	}
	
	$sql = "SELECT id,act_type FROM tb_actcode_type";
	$actTypes = $db->getAll($sql);
	
	//平台列表
	$platforms = getPlatforms();
	
	//服务器列表
	$server_list = getServerInfo();
	
	$T->assign('platforms',$platforms);
	$T->assign('server_list',$server_list);
	
	$T->assign('page',showpage($page, $pagesize, $count, $url));
	$T->assign('act',$act);
	$T->assign('actTypes',$actTypes);
	$T->assign('codes',$codes);
	$T->display('active_code.html');
	exit;
}



/**
 * 生成随机码
 * @param int $length
 * @return array 随机码数组
 */
function generatePassword($length=8)
{
    $chars = array_merge(
    				 	range(0,9),
                     	range('a','z'),
                    	range('A','Z'),
                     	array('!','@','$','%','^','&','*'));
    shuffle($chars);
    $password = '';
    for($i=0; $i<$length; $i++) {
        $password .= $chars[$i];
    }
    return $password;
}

/**
 * 央服卡号发送至单服后，更新状态
 * @param unknown_type $operate
 * @param unknown_type $codes
 * @return 1 更新成功;0 更新失败
 */
function code_send_status($operate,$codes,$server)
{
	global $db;
	$server = implode('|', $server);
	foreach($codes  as $k=>$v)
	{
		if($operate == 'add')
		{
			$id = $v['id'];
			$sql = "UPDATE tb_ad_activity_code SET `status` = 2, server_id =' $server',last_modified_date = NOW()  WHERE id = $id";		//status=2已使用，发送至单服
		}
		else 
		{
			$id = $v['id'];
			$sql = "DELETE FROM tb_ad_activity_code  WHERE id = $id";			//单服已经删除,本地也一起删除
		}
		$flag = $db->query($sql);
		
		if($flag)
		{
			continue;
		}
		else 
		{
			return $id;
		}
	}
	return true;
}

/**
 * 返回尚未使用的礼品卡号
 * @param unknown_type $codes
 */
function check_is_send($codes,$isdelete)
{
	global $db;
	$temp = array();
	foreach($codes as $k=>$v)
	{
		if($v['status'] == 2)		//已发送
		{
			if($isdelete == 1)	//发送
			{
				continue;
			}
			else 
			{
				$temp[] = $v;
			}
		}
		else if($v['status'] == 1)		//未发送
		{
			if($isdelete == 1)
			{
				$temp[] = $v;
			}
			else 
			{
				continue;
			}
		}
	}
	return $temp;
}





